package com.ly.system.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.core.TemplateClassResolver;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.web.util.HtmlUtils;

import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * markdown工具类
 *
 * @author luoyun
 * @Date: 2025/6/29 23:04
 * @Note:
 */
@Slf4j
@NoArgsConstructor
public class HTMLUtils {
    public static String getInnerText(String html) {
        if (StringUtils.isNotBlank(html)) {
            String content = html.replaceAll("</?[^>]+>", "");
            content = content.replaceAll("(&nbsp;)+", "&nbsp;");
            content = HtmlUtils.htmlUnescape(content);
            return content.trim();
        } else {
            return "";
        }
    }

    public static String parseMarkdown(String markdownContent) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdownContent);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    public static Configuration getConfig() {
        Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        config.setTemplateLoader(stringTemplateLoader);
        config.setNumberFormat("0.#####################");
        config.setClassicCompatible(true);
        config.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
        return config;
    }

    public static String parseTemplateContent(String tplContent, Map<String, Object> paras, boolean keepSpace) {
        Configuration config = HTMLUtils.getConfig();
        StringTemplateLoader stringTemplateLoader = (StringTemplateLoader) config.getTemplateLoader();
        try {
            String sqlUnderline = "sql_";
            StringWriter swriter = new StringWriter();
            if (stringTemplateLoader.findTemplateSource(sqlUnderline + tplContent.hashCode()) == null) {
                stringTemplateLoader.putTemplate(sqlUnderline + tplContent.hashCode(), tplContent);
            }
            Template mytpl = config.getTemplate(sqlUnderline + tplContent.hashCode(), "utf-8");
            if (paras.containsKey("DaoFormat")) {
                throw new RuntimeException("DaoFormat 是 minidao 保留关键字，不允许使用 ，请更改参数定义！");
            } else {
                paras.put("DaoFormat", new SimpleDateFormat());
                mytpl.process(paras, swriter);
                String sql = getSqlText(swriter.toString(), keepSpace);
                paras.remove("DaoFormat");
                return sql;
            }
        } catch (Exception var7) {
            log.error(var7.getMessage(), var7.fillInStackTrace());
            log.error("发送一次的模板key:{ " + tplContent + " }");
            throw new RuntimeException("解析SQL模板异常");
        }
    }

    private static String getSqlText(String sql, boolean keepSpace) {
        sql = Pattern.compile("(?ms)/\\*.*?\\*/|^\\s*//.*?$").matcher(sql).replaceAll("");
        if (!keepSpace) {
            sql = sql.replaceAll("\\n", " ").replaceAll("\\t", " ").replaceAll("\\s{1,}", " ").trim();
        }
        String whereSpace = "where ";
        String whereAnd = "where and";
        String commaWhere = ", where";
        String commaSpace = ", ";
        if (sql.endsWith("where") || sql.endsWith(whereSpace)) {
            sql = sql.substring(0, sql.lastIndexOf("where"));
        }
        int index;
        for (index = 0; (index = StringUtils.indexOfIgnoreCase(sql, whereAnd, index)) != -1; sql = sql.substring(0, index + 5) + sql.substring(index + 9, sql.length())) {
        }
        for (index = 0; (index = StringUtils.indexOfIgnoreCase(sql, commaWhere, index)) != -1; sql = sql.substring(0, index) + sql.substring(index + 1, sql.length())) {
        }
        if (sql.endsWith(",") || sql.endsWith(commaSpace)) {
            sql = sql.substring(0, sql.lastIndexOf(","));
        }
        return sql;
    }
}
